package com.sofun.ai.controller;

import com.sofun.ai.assistant.AiAssistant;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.service.TokenStream;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController()
@RequestMapping("/ai")
public class ChatController {

    @Resource
    QwenChatModel qwenChatModel;

    @Resource
    AiAssistant aiAssistant;

    @GetMapping("/chat")
    public String chat(String message) {
        return qwenChatModel.chat(message);
    }


    @RequestMapping(value = "/memory_chat_id")
    public String memoryChatWithId(@RequestParam(defaultValue="我叫张佳伟") String message,@RequestParam int memoryId) {
        return aiAssistant.chat(memoryId,message);
    }


    /**
     *使用流式输出
     * */
    @RequestMapping(value = "/memory_stream_chat",produces ="text/stream;charset=UTF-8")
    public Flux<String> memoryStreamChat(@RequestParam(defaultValue="我是谁") String message,
                                         @RequestParam int memoryId) {
        TokenStream stream = aiAssistant.stream(memoryId,message);

        return Flux.create(sink -> stream.onPartialResponse(sink::next)
                .onCompleteResponse(c -> sink.complete())
                .onError(sink::error)
                .start());
    }

}
